package com.jzo2o.foundations.handler;

import com.jzo2o.api.foundations.dto.response.RegionSimpleResDTO;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.model.dto.response.ServeAggregationSimpleResDTO;
import com.jzo2o.foundations.service.HomeService;
import com.jzo2o.foundations.service.IRegionService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * springCache缓存同步任务
 **/
@Slf4j
@Component
public class SpringCacheSyncHandler {

    @Resource
    private IRegionService regionService;
    @Resource
    private RedisTemplate redisTemplate;
    @Autowired
    private HomeService homeService;

    /**
     * 已启用区域缓存更新
     * 每日凌晨1点执行
     */
    @XxlJob(value = "activeRegionCacheSync")
    public void activeRegionCacheSync () {
        log.info (">>>>>>>>开始进行缓存同步，更新已启用区域");
        //1.清理缓存
        String key = RedisConstants.CacheName.JZ_CACHE + "::ACTIVE_REGIONS";
        redisTemplate.unlink (key);

        //2.刷新缓存
        List<RegionSimpleResDTO> regionSimpleResDTOS = regionService.queryActiveRegionListCache ();

        //遍历区域列表
        for (RegionSimpleResDTO region : regionSimpleResDTOS) {
            String regionKeyICON = RedisConstants.CacheName.SERVE_ICON + "::" + region.getId ();
            //删除缓存
            redisTemplate.unlink (regionKeyICON);
            //刷新缓存
            homeService.firstPageServeList (region.getId ());

            String regionKeyTYPE = RedisConstants.CacheName.SERVE_TYPE + "::" + region.getId ();
            redisTemplate.unlink (regionKeyTYPE);
            homeService.serveTypeList (region.getId ());

            String regionKeyHOT = RedisConstants.CacheName.HOT_SERVE + "::" + region.getId ();
            redisTemplate.unlink (regionKeyHOT);
            List<ServeAggregationSimpleResDTO> hotServeList = homeService.hotServeList (region.getId ());
            for (ServeAggregationSimpleResDTO dto : hotServeList) {
                Long id = dto.getId ();
                String serveKey = RedisConstants.CacheName.SERVE + "::" + id;
                redisTemplate.unlink (serveKey);
                homeService.getServeById (id);

                String serveItemKey = RedisConstants.CacheName.SERVE_ITEM + "::" + dto.getServeItemId ();
                redisTemplate.unlink (serveItemKey);
                homeService.getServeItemById (dto.getServeItemId ());
            }

        }
        log.info (">>>>>>>>更新已启用区域完成");
    }

}